<?php
/**
 *
 * 功能说明：用户控制器。
 *
 **/
namespace Team\Controller;
use Think\Controller;
use Vendor\Tree;
class MemberController extends ComController {

    //用户列表
    public function index(){

        $p = isset($_GET['p'])?intval($_GET['p']):'1';
        $keyword = isset($_GET['keyword'])?$_GET['keyword']:'';
        $dept = isset($_GET['dept'])?intval($_GET['dept']):'';
        $where = '';

        $prefix = C('DB_PREFIX');
        if($keyword <>''){
            $where ="{$prefix}member.email LIKE '%$keyword%' OR {$prefix}member.qq LIKE '%$keyword%' OR {$prefix}member.phone LIKE '%$keyword%' OR {$prefix}member.user LIKE '%$keyword%' OR {$prefix}member.name LIKE '%$keyword%' OR {$prefix}member.tel LIKE '%$keyword%'";
        }

        if($dept <>''){
            $where= "{$prefix}member.dept_id='{$dept}'";
        }

        $user = M('member');
        $pagesize = 10;#每页数量
        $offset = $pagesize*($p-1);//计算记录偏移量
        $count = $user->where($where)->count();

        $list  = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title,{$prefix}department.name as dept_name")
            ->order("{$prefix}member.t desc")
            ->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid",'left')
            ->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}auth_group_access.group_id",'left')
            ->join("{$prefix}department ON {$prefix}department.id = {$prefix}member.dept_id",'left')
            ->where($where)
            ->limit($offset.','.$pagesize)->select();

        //$user->getLastSql();
        $page	=	new \Think\Page($count,$pagesize);
        $page = $page->show();
        $this->assign('list',$list);
        $this->assign('page',$page);
        $group = M('auth_group')->field('id,title')->select();
        $this->assign('group',$group);
        $this -> display();
    }

    public function del(){

        $uids = isset($_REQUEST['uids'])?$_REQUEST['uids']:false;
        $uids = json_decode($uids,true);
        //uid为1的禁止删除
        if($uids==1 or !$uids){
            $info = array(
                "info"=>"参数错误",
                "status"=>"n",
            );
            $this -> ajaxReturn($info,'json');
        }
        if(is_array($uids))
        {
            foreach($uids as $k=>$v){
                if($v['uids']==1){//uid为1的禁止删除
                    unset($uids[$k]);
                }
                $uids[$k] = intval($v['uids']);
            }
            if(!$uids){
                $info = array(
                    "info"=>"参数错误",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
                $uids = implode(',',$uids);
            }
        }
//        dump($uids);die;
        $map['uid']  = array('in',$uids);
        if(M('member')->where($map)->delete()){
            M('auth_group_access')->where($map)->delete();
            addlog('删除会员UID：'.$uids);
            $info = array(
                "info"=>"恭喜,操作成功！",
                "status"=>"y",
            );
            $this -> ajaxReturn($info,'json');
        }else{
            $info = array(
                "info"=>"参数错误",
                "status"=>"n",
            );
            $this -> ajaxReturn($info,'json');
        }
    }

    public function edit(){

        $uid = isset($_GET['uid'])?intval($_GET['uid']):false;
        if($uid){
            //$member = M('member')->where("uid='$uid'")->find();
            $prefix = C('DB_PREFIX');
            $user = M('member');
            $member  = $user->field("{$prefix}member.*,{$prefix}auth_group_access.group_id")
                ->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid",'LEFT')
                ->where("{$prefix}member.uid='{$uid}'")
                ->find();
//            dump($member);die;
        }else{
            $this->ajaxReturn('参数错误！');
        }

        $department = M('department')->field('id,pid,name,time')->order('time asc')->select();
        $tree = new Tree($department);
        $str = "<option value=\$id \$selected>\$spacer\$name</option>"; //生成的形式
        $department = $tree->get_tree(0,$str,$member['dept_id']);

        $usergroup = M('auth_group')->field('id,title')->select();
        $this->assign('usergroup',$usergroup);
        $this->assign('department',$department);
        $this->assign('member',$member);
        $this -> display();
    }

    public function add(){
        $department = M('department')->field('id,pid,name,time')->order('time asc')->select();
        $tree = new Tree($department);
        $str = "<option value=\$id \$selected>\$spacer\$name</option>"; //生成的形式
        $department = $tree->get_tree(0,$str);
        $usergroup = M('auth_group')->field('id,title')->select();
        $this->assign('usergroup',$usergroup);
        $this->assign('department',$department);
        $this -> display();
    }

    public function update($ajax=''){
        if($ajax=='yes'){
            $uid = I('get.uid',0,'intval');
            $gid = I('get.gid',0,'intval');
            if($uid !==1){
                M('auth_group_access')->data(array('group_id'=>$gid))->where("uid='$uid'")->save();
                die('1');
            }
        }

        $uid = isset($_POST['uid'])?intval($_POST['uid']):false;
        $user = isset($_POST['user'])?htmlspecialchars($_POST['user'], ENT_QUOTES):'';
        $group_id = isset($_POST['group_id'])?intval($_POST['group_id']):0;
        if(!$group_id){
            $info = array(
                "info"=>"请选择用户组！",
                "status"=>"n",
            );
            $this -> ajaxReturn($info,'json');
        }
        $password = isset($_POST['password'])?trim($_POST['password']):false;
        if($password) {
            $data['password'] = password($password);
        }
        $head = I('post.head','','strip_tags');
        $token = password(uniqid(rand(), TRUE));
        $salt = random(10);
        $identifier = password($user['uid'].md5($user['user'].$salt));
        $auth = $identifier.','.$token;
        $data['sex'] = isset($_POST['sex'])?intval($_POST['sex']):0;
        $data['dept_id'] = isset($_POST['dept_id'])?intval($_POST['dept_id']):0;
        $data['head'] = $head?$head:'';
        $data['birthday'] = isset($_POST['birthday'])?strtotime($_POST['birthday']):0;
        $data['phone'] = isset($_POST['phone'])?trim($_POST['phone']):'';
        $data['qq'] = isset($_POST['qq'])?trim($_POST['qq']):'';
        $data['email'] = isset($_POST['email'])?trim($_POST['email']):'';
        $data['tel'] = isset($_POST['tel'])?trim($_POST['tel']):'';
        $data['type'] = isset($_POST['type_id'])?trim($_POST['type_id']):'';
        $data['rank'] = isset($_POST['rank'])?trim($_POST['rank']):'';
        $data['name'] = isset($_POST['name'])?trim($_POST['name']):'';
        $data['identifier'] =$identifier;
        $data['token'] = $token;
        $data['salt'] =$salt;

        if(!$uid){
            if($user==''){
                $info = array(
                    "info"=>"用户名称不能为空！",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
            }
            if(!$password){
                $info = array(
                    "info"=>"用户密码不能为空！",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
            }
            if(M('member')->where("user='{$user}'")->count()){
                $info = array(
                    "info"=>"用户名已被占用！",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
            }
            $data['t'] = time();
            $data['created'] = time();
            $data['user'] = $user;
            $uid = M('member')->data($data)->add();
            M('auth_group_access')->data(array('group_id'=>$group_id,'uid'=>$uid))->add();
            addlog('新增会员，会员UID：'.$uid);
        }else{
            M('auth_group_access')->data(array('group_id'=>$group_id))->where("uid=$uid")->save();
            M('member')->data($data)->where("uid=$uid")->save();
            addlog('编辑会员信息，会员UID：'.$uid);
        }
        $info = array(
            "info"=>"操作成功！",
            "status"=>"n",
        );
        $this -> ajaxReturn($info,'json');
    }


    //日志管理
    public function logs($p=1){

        $keyword = isset($_GET['keyword'])?$_GET['keyword']:'';
        $options = isset($_GET['options'])?$_GET['options']:'';

        $p = intval($p)>0?$p:1;

        $pagesize = 20;#每页数量
        $offset = $pagesize*($p-1);//计算记录偏移量

        //获取日期条件
        switch($options){
            case 'day':
                $today = strtotime(date('Y-m-d',time()));
                $where = "t >='{$today}'";
                break;

            case 'week':
                $week = strtotime('last week');
                $where = "t >='{$week}'";
                break;

            case 'month':
                $month = strtotime("-1 month");
                $where = "t >='{$month}'";
                break;

            default:
                $month = strtotime("-36 month");
                $where = "t >='{$month}'";
                break;
        }

        //搜索条件
        if($keyword <> ''){
            $where .=" AND log LIKE '%$keyword%' OR ip LIKE '%$keyword%' OR name LIKE '%$keyword%'";
        }

        $count = M('log')->where($where)->count();
        $list = M('log')->where($where)->order('t desc')->limit($offset.','.$pagesize)->select();

        $page	=	new \Think\Page($count,$pagesize);
        $page = $page->show();

        $this->assign('list',$list);
        $this->assign('page',$page);

        $this->display();

    }
}

